package com.itcam.lease.web.admin.custom.interceptor;

import com.itcam.lease.common.context.LoginUserContext;
import com.itcam.lease.common.exception.LeaseException;
import com.itcam.lease.common.result.ResultCodeEnum;
import com.itcam.lease.common.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取 access_token
        String token = request.getHeader("access_token");

        // 如果 token 为空，则抛出异常，表示用户未登录
        if (token == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        } else {
            // 解析 token，获取其中的用户信息
            Claims claims = JWTUtil.parseToken(token);
            // 从 claims 中获取 userId 和 username
            Long userId = claims.get("userId", Long.class);
            String username = claims.get("username", String.class);
            // 将用户信息设置到上下文中
            LoginUserContext.setLoginUser(userId, username);
        }
        // 返回 true，表示请求可以继续处理
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在请求处理完成后，清除上下文中的用户信息
        LoginUserContext.clear();
    }
}

